// 商品管理
import React, { useState, useEffect } from 'react';
import { Select, Space, Button, Form, Table, DatePicker, Switch, Image, Modal, message, ConfigProvider } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ExclamationCircleFilled } from '@ant-design/icons';
import type { TableRowSelection } from 'antd/es/table/interface';
import AddorRev from './oShopChild/AddorRev';
import zh_CN from 'antd/es/locale/zh_CN';
import '../../css/operation.css'
import { useNavigate } from 'react-router-dom'
import { getShop, delShop } from '../../../api/opreationApi'
// 表格
interface DataType {
  key: React.Key;
  goodsId: number;
  brandName: string;//品牌
  categoryName: string;//分类
  goodsName: string;//商品名称
  goodsSerNum: string;//货号
  goodsPriceRange: string;//价格
  goodsImg: string;//图片
  goodsSell: string;//销量
  state: number
  location: number
}

//日期选择
const { RangePicker } = DatePicker;

export default function OperationSlide() {
  const [shopData, setShopData] = useState<DataType[]>([])//当前页渲染数据
  const [pageSize, setPageSize] = useState<number>(5) //每页条数
  const [currentPage, setCurrentPage] = useState<number>(1) //当前第几页
  const [total, setTotal] = useState<number>()//总条数
  const [sortWay, setSortWay] = useState<string>()//选择排序方式
  const [tsaId, setTsaId] = useState<Number | null>(null)
  // 拿初始数据函数 查询 排序
  const getData = () => {
    setTsaId(Number(sessionStorage.getItem('tsaId')))
    getShop({
      currentPage, pageSize, sortWay, tsaId
    }).then(res => {
      const arr = res.data.vyyGoods.map((item:any) => ({
        location: item.location,
        state: item.state,
        ...item.vyyGoods
      }))
      setShopData(arr)
      setTotal(res.data.total)
    })
  }

  // 请求数据渲染页面
  useEffect(() => {
    getData()
  }, [pageSize, currentPage, sortWay, tsaId])
  // 路由
  const navigate = useNavigate()
  // 表格
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'goodsId',
    },
    {
      title: '商品图片',
      dataIndex: 'goodsImg',
      render: (_, record) => (
        <Image
          width={50}
          height={50}
          src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
        />
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
    },
    {
      title: '货号',
      dataIndex: 'goodsSerNum',
    },
    {
      title: '价格',
      dataIndex: 'goodsPriceRange',
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
    },
    {
      title: '销量',
      dataIndex: 'goodsSell',
    },
    {
      title: '位置',
      dataIndex: 'location',
      render: (_, record) => (
        record.location ? record.location : '待设'
      ),
    },
    {
      title: '是否上架',
      dataIndex: 'state',
      render: (_, record) => (
        <Switch defaultChecked={record.state === 1 ? true : false} />
      ),
    },
    {
      title: '操作',
      dataIndex: 'address',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" className='edmit' onClick={() => revLocation(record)}>位置</Button>
          <Button id='del' onClick={() => showConfirm(record)}>移除</Button>
        </Space >
      ),
    },
  ];
  const rowSelection: TableRowSelection<DataType> = {
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
        },
      },
    ],
  };

  // 操作部分
  // （1）删除
  // 删除弹框
  const { confirm } = Modal;
  const showConfirm = (record: any) => {
    confirm({
      title: '提示:',
      icon: <ExclamationCircleFilled />,
      content: '您确定要移除吗？移除后无法恢复！',
      cancelText: '取消',
      okText: '确认',
      onOk() {
        // 点击确定发起请求
        delShop(
          {
            tsaId: Number(sessionStorage.getItem('tsaId')),
            goodsId: record.goodsId
          }).then(res => {
            getData()
          })
      },
    });
  };

  // （2）添加和编辑共用弹框
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);//是否显示对话框
  const [nowRow, setNowRow] = useState<any>(null)
  // 添加
  const add = () => {
    navigate('/home/operations/addShop')
  }
  // 编辑
  const revLocation = (record: any): void => {
    setNowRow(record)
    setIsModalOpen(true)
  }

  //下拉框
  const handleChange = (value: string) => {
    setSortWay(value)
  };

  // 自定义添加编辑弹框消失
  const modalClose = () => {
    setIsModalOpen(false);
  }
  // 表 格
  return (<div>
    {/* 头部标题 */}
    <p className='head opHead'>商品管理</p>
    {/* 表格列表整体 */}
    <div className='table'>
      {/* 表格操作 */}
      <div className='operationTable'>
        {/* 排序 */}
        <Form>
          <Form.Item label='排序：' className='operate-left-item' name='state'>
            <Space wrap>
              <Select
                onChange={handleChange}
                style={{ width: 120 }}
                allowClear
                options={[{ value: '按序号顺序', label: '按序号顺序' }, { value: '按序号倒序', label: '按序号倒序' }]}
                className='drop'
                placeholder="选择排序方式"
              />
            </Space>
          </Form.Item>
        </Form>
        <Button className='add' onClick={add}>添加</Button>
      </div>
      {/* 表格 */}
      <ConfigProvider locale={zh_CN}>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={shopData}
          rowKey={item => item.goodsId}
          pagination={{
            position: ['bottomRight'],
            defaultPageSize: 6,
            pageSizeOptions: [3, 5, 10, 15],
            showQuickJumper: true,
            showSizeChanger: true,
          }} />
      </ConfigProvider>
    </div>
    {/* 增加编辑共用弹框 */}
    <AddorRev nowRow={nowRow} modalClose={modalClose} isModalOpen={isModalOpen} getData={getData}></AddorRev>
  </div >)
}
